package com.bokee.archerwq.lab.mina.server;

import java.text.SimpleDateFormat;
import java.util.Random;

import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bokee.archerwq.lab.mina.message.Request;
import com.bokee.archerwq.lab.mina.message.Response;

public class TimeServerHandler extends IoHandlerAdapter {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		logger.error(cause.getClass().getName(), cause);
		session.close();
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		Request request = (Request) message;
		logger.info("message recieved:[" + request.getId() + "]");
		Response response = new Response();
		response.setReqId(request.getId());
		response.setDateTime(getDateTime());
		Random ran = new Random();
		Thread.sleep(ran.nextInt(8 * 1000));
		session.write(response);
	}

	private String getDateTime() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss",
				java.util.Locale.CHINA);
		return sdf.format(new java.util.Date());
	}

}
